<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\UserDistribution;
use app\common\model\UserBeansLog;
use app\common\model\UserScoreLog;
use app\common\model\Config;
use app\common\model\Order;
use app\common\model\User;
use think\Db;
use addons\third\model\Third;

/**
 * 会员
 */
class Member extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['wxOfficialAccountBaseLogin','init'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 商家入驻
     * @DateTime 2023-04-23T16:13:57+0800
     * @return   [type]                   [description]
     */
    public function merchantSettlement()
    {
        $name = input('name','','htmlspecialchars,strip_tags');
        $address = input('address','','htmlspecialchars,strip_tags');
        $contact_user = input('contact_user','','htmlspecialchars,strip_tags');
        $phone = input('phone','','htmlspecialchars,strip_tags');
        $data = [
            'name'=>$name,
            'address'=>$address,
            'contact_user'=>$contact_user,
            'phone'=>$phone,
        ];
        $rule = [
            'name' => "require",
            'address' => "require",
            'contact_user' => "require",
            'phone' => "require",
        ];
        $msg = [
            'name.require' => '请填写商家门店名称',
            'address.require' => '请填写商家门店定位',
            'contact_user.require' => '请填写联系人',
            'phone.require' => '请填写联系电话',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) $this->error($validate->getError());
        $data['user_id'] = $this->auth->id;
        Db::name('merchant_settlement')->insert($data);
        $this->success('提交成功');
    }

    /**
     * 我的团员
     * @DateTime 2023-04-25T20:20:30+0800
     * @return   [type]                   [description]
     */
    public function memberList()
    {
        $user_id = $this->auth->id;
        $page = input('page',1);
        $is_yx = input('is_yx',0);
        $pageSize = 20;
        if ($is_yx) {
            $user = Db::name('user')->alias('u')->join('chbc_user_distribution ud','ud.pid=u.id')->field('u.id,u.nickname,u.avatar')->where(['u.pid'=>$user_id,'u.status'=>'normal'])->group('u.id')->page($page,$pageSize)->select();
        } else {
            $user = Db::name('user')->alias('u')->field('u.id,u.nickname,u.avatar')->where(['u.pid'=>$user_id,'u.status'=>'normal'])->page($page,$pageSize)->select();
        }
        $list = [];
        $yx = 0;
        foreach ($user as $key => $value) {
            $list[$key] = $value;
            $user_distribution = Db::name('user_distribution')->field('sum(amount) as amount,max(order_times) as order_times,create_dt')->where(['uid'=>$value['id'],'status'=>1])->find();
            // if (isset($user_distribution['amount']) && $user_distribution['amount']) {
            //     $yx+=1;
            // }
            $list[$key]['amount'] = (float)$user_distribution['amount'];
            $list[$key]['order_times'] = (int)$user_distribution['order_times'];
            $list[$key]['create_dt'] = $user_distribution['create_dt']?$user_distribution['create_dt']:'';
        }
        $sql = 'select uid,sum(amount) as amount from chbc_user_distribution where pid='.$user_id.' and status=1 group by uid';
        $user_distributions = Db::query($sql);
        foreach ($user_distributions as $key => $v) {
            if (isset($v['amount']) && $v['amount']) {
                $yx+=1;
            }
        }
        $total_user = Db::name('user')->field('id,nickname,avatar')->where(['pid'=>$user_id,'status'=>'normal'])->count();
        $total_amount = (float)Db::name('user_distribution')->where(['pid'=>$user_id,'status'=>1])->value('sum(amount)');
        $this->success('团队收益',['list'=>$list,'total_user'=>$total_user,'total_amount'=>$total_amount,'yx'=>$yx]);
    }


    /**
     * 收益明细
     * @DateTime 2023-04-25T21:08:52+0800
     * @return   [type]                   [description]
     */
    public function revenueDetails()
    {
        $user_id = $this->auth->id;
        $page = input('page',1);
        $pageSize = 20;
        $list = [];
        $user_distribution = Db::name('user_distribution')->alias('ud')->join('chbc_user u','ud.uid=u.id')->field('ud.amount,ud.order_times,ud.create_dt,u.avatar,u.nickname')->where(['ud.pid'=>$user_id,'ud.status'=>1])->order('ud.id DESC')->page($page,$pageSize)->select();
        $total = Db::name('user_distribution')->where(['pid'=>$user_id,'status'=>1])->count();
        foreach ($user_distribution as $key => $value) {
            $list[$key] = $value;
            $list[$key]['text'] = '团员 '.$value['nickname'].' 下单';
            if ($value['order_times']==1) {
                $list[$key]['text'] = '团员 '.$value['nickname'].' 首次下单';
            }
            if ($value['order_times']==2) {
                $list[$key]['text'] = '团员 '.$value['nickname'].' 第二次下单';
            }
        }
        $total_user = Db::name('user')->field('id,nickname,avatar')->where(['pid'=>$user_id,'status'=>'normal'])->count();
        $total_amount = Db::name('user_distribution')->where(['pid'=>$user_id,'status'=>1])->value('sum(amount)');
        $this->success('收益明细',['list'=>$list,'total_user'=>$total_user,'total_amount'=>$total_amount,'total'=>$total]);
    }

    /**
     * 个人收益
     * @DateTime 2023-04-23T15:02:57+0800
     * @return   [type]                   [description]
     */
    public function beansList()
    {
        $page = input('page',1);
        $pageSize = 20;
        $user_id = $this->auth->id;
        $UserBeansLog = new UserBeansLog();
        $extend['log_type'] = ['<>',3];
        $res = $UserBeansLog->getList($user_id,$page,$extend,$pageSize);
        $list = $res['list'];
        foreach ($list as $key => &$value) {
            if (intval($value['tran_no'])==0) {
                $order = Db::name('mtofficial_order')->where('play_order_no',$value['tran_no'])->field('content')->find();
                if ($order) {
                    $content = json_decode($order['content'],1);
                    if (isset($content['picture'])) $value['delete_dt'] = $content['picture'];
                } else {
                    $order = Db::name('play_order')->where('yunzhan_order_no',$value['tran_no'])->field('proposal')->find();
                    if ($order) {
                        $content = json_decode($order['proposal'],1);
                        if (isset($content['logo'])) $value['delete_dt'] = $content['logo'];
                    }
                }
            } else {
                $order = Db::name('mtofficial_order')->where('play_order_no',$value['tran_no'])->field('content,is_yunzhan')->find();
                if ($order) {
                    $content = json_decode($order['content'],1);
                    if ($content) {
                        if ($order['is_yunzhan']==4) {
                            $value['delete_dt'] = $content['picture'];
                        } elseif ($order['is_yunzhan']==5) {
                            $value['delete_dt'] = $content['shop_picture'];
                        }
                    }
                } else {
                    $order = Db::name('play_order')->where('play_order_no',$value['tran_no'])->field('shop_no')->find();
                    if ($order) {
                        $shop = Db::name('shop')->where('shop_no',$order['shop_no'])->field('logo_pic,id')->find();
                        $value['delete_dt'] = config('upload_domain').$shop['logo_pic'];
                    }
                }
            }
            if ($value['delete_dt']==config('upload_domain')) $value['delete_dt'] = $this->auth->avatar;
        }
        $this->success('个人收益',['list'=>$list,'total'=>$res['total']]);
    }


    /**
     * 会员中心
     * @DateTime 2023-04-27T14:17:45+0800
     * @return   [type]                   [description]
     */
    public function center()
    {
        $user_id = $this->auth->id;
        $user = User::get($user_id);
        $score = $user['score'];
        $level = $user['level'];
        $level2 = $level+1;
        // 邀请获得积分数
        $invite_score = config('invite_score');
        // 订单获得积分数
        $order_score = config('order_score');
        $vip[1] = ['邀请有效成员数量'=>0,'完成订单数量'=>0];
        $vip[2] = Config::getConfigs('growth_conditions2');
        $vip[3] = Config::getConfigs('growth_conditions3');
        $vip[4] = Config::getConfigs('growth_conditions4');
        $vip[5] = Config::getConfigs('growth_conditions5');
        $levelscore = [];
        for ($i=1; $i <= 5; $i++) { 
            if ($i==1) $levelscore[$i] = 0;
            if ($i>1) $levelscore[$i] = $levelscore[$i-1];
            if ($vip[$i]['邀请有效成员数量']) $levelscore[$i] += round($vip[$i]['邀请有效成员数量']*$invite_score);
            if ($vip[$i]['完成订单数量']) $levelscore[$i] += round($vip[$i]['完成订单数量']*$order_score);
            
        }
        // 升级需要的订单和用户
        $order_num = UserScoreLog::where(['user_id'=>$user_id,'log_type'=>2,'level'=>['>=',$level]])->count();
        $invite_num = UserScoreLog::where(['user_id'=>$user_id,'log_type'=>3,'level'=>['>=',$level]])->count();
        $order_num_diff = $vip[$level2]['完成订单数量']-$order_num;
        $invite_num_diff = $vip[$level2]['邀请有效成员数量']-$invite_num;
        if ($order_num_diff<0) $order_num_diff=0;
        if ($invite_num_diff<0) $invite_num_diff=0;
        $text = '';
        if ($level<5) {
            $num = $order_num_diff*$order_score+$invite_num_diff*$invite_score;
            // $num = $levelscore[$level2]-$score;
            $text = sprintf("还差%s成长值升级至VIP%u",$num,$level2);
        } else {
            $level2 = '';
        }
        $task = [
            'invite' => [
                'now'=>$invite_num>$vip[$level+1]['邀请有效成员数量']?$vip[$level+1]['邀请有效成员数量']:$invite_num,
                'sum' => $vip[$level+1]['邀请有效成员数量'],
            ],
            'order' => [
                'now'=>$order_num>$vip[$level+1]['完成订单数量']?$vip[$level+1]['完成订单数量']:$order_num,
                'sum' => $vip[$level+1]['完成订单数量'],
            ],
        ];
        //  累积返现
        $ljfx = UserBeansLog::where(['log_type'=>1,'user_id'=>$user_id])->value('sum(beans)');
        // 外卖收益
        $wmsy = UserBeansLog::where(['log_type'=>['in',[1,3,6]],'user_id'=>$user_id])->value('sum(beans)');
        // 电商收益
        $dssy = (float)UserBeansLog::where(['log_type'=>10,'user_id'=>$user_id])->value('sum(beans)');
        // 累计收益
        $ljsy = round($wmsy+$dssy,2);
        // 我的订单
        $wddd = order_count_read($user_id);
        $wddd=intval($wddd+Db::name('tk_order_detail_commission')->where('tk_user_id',$user_id+config('virtual_userid'))->count(1));
        // 我的卡券
        $wdkq = \app\common\model\UserRoll::where(['user_id'=>$user_id,'status'=>1])->value('sum(roll_num)');
        // 我的收藏(只计算电商)
        $wdsc = Db::name('tk_goodscollect')->where(['tk_user_id'=>$user_id+config('virtual_userid')])->count(1);
        $benefits = [];
        $arr1 = ['card_one','card_two','card_three','card_five'];
        $arr2 = [];
        foreach ($arr1 as $key => $value) {
            $arr2[] = Db::name('config')->where('name',$value)->value('value');
        }
        $benefits[1] = Db::name('config')->where('name','membership_benefits1')->value('value');
        $benefits[1] = str_replace($arr1,$arr2,$benefits[1]);
        $benefits[1] = json_decode($benefits[1],1);
        $benefits[2] = Db::name('config')->where('name','membership_benefits2')->value('value');
        $benefits[2] = str_replace($arr1,$arr2,$benefits[2]);
        $benefits[2] = json_decode($benefits[2],1);
        $benefits[3] = Db::name('config')->where('name','membership_benefits3')->value('value');
        $benefits[3] = str_replace($arr1,$arr2,$benefits[3]);
        $benefits[3] = json_decode($benefits[3],1);
        $benefits[4] = Db::name('config')->where('name','membership_benefits4')->value('value');
        $benefits[4] = str_replace($arr1,$arr2,$benefits[4]);
        $benefits[4] = json_decode($benefits[4],1);
        $benefits[5] = Db::name('config')->where('name','membership_benefits5')->value('value');
        $benefits[5] = str_replace($arr1,$arr2,$benefits[5]);
        $benefits[5] = json_decode($benefits[5],1);
        $earn = [1=>'340',2=>'1020',3=>'2550',4=>'5100',5=>'5100'];
        $list = ['vip'=>$vip,'levelscore'=>$levelscore,'benefits'=>$benefits,'earn'=>$earn];
        $data = [
            'level' => $level,
            'level2' => $level2,
            'score' => $score,
            'text' => $text,
            'task' => $task,
            'ljfx' => $ljfx,
            'dssy' => $dssy,
            'wmsy' => $wmsy,
            'ljsy' => $ljsy,
            'wddd' => $wddd,
            'wdkq' => $wdkq,
            'list' => $list,
            'wdsc' => $wdsc,
            'unlockLv' => [
                '大牌专享券' => 'lv3解锁',
                '延时券' => 'lv2解锁',
                '超值试用券' => 'lv5解锁',
                '超前抢单券' => 'lv2解锁',
            ]
        ];
        $this->success('会员中心',$data);
    }

    /**
     * 订单通知
     * @DateTime 2023-05-06T22:29:47+0800
     * @return   [type]                   [description]
     */
    public function orderNotice()
    {
        $time = time();
        $user_id = $this->auth->id;
        $page = input('page/d',1);
        $pageSize = 10;
        $total = Db::name('notice')->where('type=3 and play_order_no>0 and user_id='.$user_id)->count();
        $notice = Db::name('notice')->where('type=3 and play_order_no>0 and user_id='.$user_id)->page($page,$pageSize)->order('id DESC')->select();
        foreach ($notice as $key => &$value) {
            $shop = Db::name('play_order')->alias('po')->join('shop s','po.shop_no=s.shop_no')->field('s.shop_name,s.logo_pic')->where(['po.play_order_no'=>$value['play_order_no']])->find();
            $value['shop_name'] = $shop['shop_name'];
            $value['logo_pic'] = config('upload_domain').$shop['logo_pic'];
            $value['status'] = $value['status']==0?'未查看':'已查看';
            $createtime = strtotime($value['create_dt']);
            $value['date'] = date('Y-m-d',$createtime);
            $value['time'] = date('H:i',$createtime);
            $h = date('H',$createtime);
            $value['day'] = $h<12?'上午':'下午';
            $sub = $time-$createtime;
            if ($sub<60) {
                $time1 = $sub.'秒前';
            } elseif ($sub<3600) {
                $minite = round($sub/60);
                $time1 = $minite.'分钟前';
            } elseif ($sub<3600) {
                $hour = round($sub/3600);
                $time1 = $hour.'小时前';
            } else {
                $day = round($sub/86400);
                $time1 = $day.'天前';
            }
            $value['time1'] = $time1;
        }
        $this->success('订单通知',['list'=>$notice,'total'=>$total]);
    }

    /**
     * 服务通知
     * @DateTime 2023-05-06T22:29:47+0800
     * @return   [type]                   [description]
     */
    public function serviceNotice()
    {
        $time = time();
        $user_id = $this->auth->id;
        $page = input('page/d',1);
        $pageSize = 10;
        $total = Db::name('notice')->where('type=3 and play_order_no=0 and user_id='.$user_id)->count();
        $notice = Db::name('notice')->where('type=3 and play_order_no=0 and user_id='.$user_id)->page($page,$pageSize)->order('id DESC')->select();
        foreach ($notice as $key => &$value) {
            $value['status'] = $value['status']==0?'未查看':'已查看';
            $createtime = strtotime($value['create_dt']);
            $value['date'] = date('Y-m-d',$createtime);
            $value['time'] = date('H:i',$createtime);
            $h = date('H',$createtime);
            $value['day'] = $h<12?'上午':'下午';
            $value['url'] = '/pages/index/raffle/raffle';
            if ($value['title']=='吃豆提现成功') {
                $value['url'] = '/pages/user/user-data';
            }
            if ($value['title']=='团长奖励获得吃豆') {
                $value['url'] = '/pages/user/user-data';
            }
            $sub = $time-$createtime;
            if ($sub<60) {
                $time1 = $sub.'秒前';
            } elseif ($sub<3600) {
                $minite = round($sub/60);
                $time1 = $minite.'分钟前';
            } elseif ($sub<3600) {
                $hour = round($sub/3600);
                $time1 = $hour.'小时前';
            } else {
                $day = round($sub/86400);
                $time1 = $day.'天前';
            }
            $value['time1'] = $time1;
        }
        $this->success('服务通知',['list'=>$notice,'total'=>$total]);
    }

    /**
     * 消息中心
     * @DateTime 2023-05-06T22:48:18+0800
     * @return   [type]                   [description]
     */
    public function noticeList()
    {
        $user_id = $this->auth->id;
        $time = time();
        // 订单通知
        $count1 = (int)Db::name('notice')->where('type=3 and play_order_no>0 and status=0 and user_id='.$user_id)->count();
        // 服务通知
        $count2 = (int)Db::name('notice')->where('type=3 and play_order_no=0 and status=0 and user_id='.$user_id)->count();
        $title1 = '';
        $title2 = '';
        $time1 = '';
        $time2 = '';
        $list1 = Db::name('notice')->where('type=3 and play_order_no>0 and user_id='.$user_id)->field('title,create_dt')->order('id DESC')->find();
        if ($list1) {
            $list1['create_dt'] = strtotime($list1['create_dt']);
            $title1 = $list1['title'];
            $sub = $time-$list1['create_dt'];
            if ($sub<60) {
                $time1 = $sub.'秒前';
            } elseif ($sub<3600) {
                $minite = round($sub/60);
                $time1 = $minite.'分钟前';
            } elseif ($sub<3600) {
                $hour = round($sub/3600);
                $time1 = $hour.'小时前';
            } else {
                $day = round($sub/86400);
                $time1 = $day.'天前';
            }
        }
        $list2 = Db::name('notice')->where('type=3 and play_order_no=0 and user_id='.$user_id)->field('title,create_dt')->order('id DESC')->find();
        if ($list2) {
            $list2['create_dt'] = strtotime($list2['create_dt']);
            $title2 = $list2['title'];
            $sub = $time-$list2['create_dt'];
            if ($sub<60) {
                $time2 = $sub.'秒前';
            } elseif ($sub<3600) {
                $minite = round($sub/60);
                $time2 = $minite.'分钟前';
            } elseif ($sub<3600) {
                $hour = round($sub/3600);
                $time2 = $hour.'小时前';
            } else {
                $day = round($sub/86400);
                $time2 = $day.'天前';
            }
        }
        $data = [
            'count1' => $count1,
            'title1' => $title1,
            'time1' => $time1,
            'count2' => $count2,
            'title2' => $title2,
            'time2' => $time2,
        ];
        $this->success('消息中心',$data);
    }


    public function checkNotice()
    {
        $id = input('id/d',0);
        if ($id) {
            $notice = Db::name('notice')->where('id',$id)->find();
            if ($notice['status']==0) {
                Db::name('notice')->where('id',$id)->update([
                    'status' => 1,
                    'update_dt' => date('Y-m-d H:i:s',time())
                ]);
            }
        }
        $this->success('成功');
    }

    /**
     * h5登录
     * @DateTime 2023-04-20T15:21:15+0800
     * @return   [type]                   [description]
     */
    public function wxOfficialAccountBaseLogin()
    {
        $platform = $this->request->post("platform", 'wechat');
        $code = input('code');
        $pid = input('pid/d', 0);
        $config = get_addon_config('third');
        $config['wechat']['app_id'] = config('wx_gzh2.appid');
        $config['wechat']['app_secret'] = config('wx_gzh2.appsecret');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $platformObj = $app->{$platform};
        $result = $platformObj->getAccessToken($code);
        \think\Log::write('用户端h5获取code:'.json_encode($result,JSON_UNESCAPED_UNICODE));
        $openid = $result['openid'];
        if (empty($openid)) {
            $this->error('登陆失败', '', 400, 'json', ['statuscode' => 200]);
        }
        Db::startTrans();
        try {
            $wechatUserInfo = $platformObj->getUserInfo($result);
            \think\Log::write('用户端h5微信授权信息:'.json_encode($wechatUserInfo,JSON_UNESCAPED_UNICODE));
            // var_dump($wechatUserInfo);exit;
            $unionid = isset($wechatUserInfo['userinfo']['unionid'])?$wechatUserInfo['userinfo']['unionid']:'';
            // if ($userWechat && $userWechat['user_id'] > 0) {
            $user = (new User())->where(['unionid' => $unionid,'user_type'=>2])->find();
            // }
            if (isset($user) && $user) {
                if ($user->status != 'normal') {
                    $this->error(__('Account is locked'));
                }
                $userWechat = (new Third())->where(['platform' => 'h5', 'unionid' => $unionid,'user_id'=>$user['id']])->find();
                if (!isset($userWechat['id']) || !$userWechat['id']) {
                    $this->error('没有查询到您的账号');
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            } else {
                $this->error('没有查询到您的账号');
            }
            //用户注册成功
            if ($ret) {
                $userInfo = $this->auth->getUserinfo();
                $userInfo['session_key'] = '';
                Db::commit();
                $this->success(__('Logged in successful'), $userInfo);
            } else {
                Db::rollback();
                $this->error($this->auth->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error('登陆失败');
        }
        $this->success('', $data);
    }

    public function init()
    {

        $data = [
            'wechat' =>
            [
                'appid' => config('wx_gzh2.appid'),
                'autologin' => true,
                'redirecturl' => config('member_domain'),
            ],
            'share' => [
                'homepage' => ['title'=>'全城外卖试吃，就上吃喝不愁','desc'=>'每日外卖试吃活动更新','image'=>'https://oss.chbcplus.com/uploads/20230422/baca91c2f33a6d1270aae65ea4d3dc79.png','path'=>config('share_domain').'/#/'],
                'playinfo' => ['title'=>'XXXXX店铺外卖福利','desc'=>'最低只需XX元','image'=>''],
            ],
            'h5_domain' => config('h5_domain').'/#/',
        ];
        $this->success('初始化数据', $data);
    }

}
